package team.stride.tabs.settings;

import org.json.JSONException;
import org.json.JSONObject;

import team.stride.R;
import team.stride.database.StrideDB;
import team.stride.database.crud.users.UsersItem;
import team.stride.tabs.TabGroupActivity;
import team.stride.utils.UtilsStride;
import twitter4j.TwitterException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.facebook.android.BaseRequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionEvents;
import com.facebook.android.Util;
import com.facebook.android.Facebook.DialogListener;
import com.twitter.TwitterLogin;

public class SettingsActivity extends Activity
{
	private Button fButton;
	private Button tButton;
	private Button fLogout;
	private Button tLogout;
	private Button music;
	private Spinner playlist_spinner;

	private TextView fUser;
	private TextView tUser;

	private Handler mHandler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		View v = LayoutInflater.from(getParent()).inflate(R.layout.settings_layout, null);
		setContentView(v);
		
		initListenersGUI();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		refreshGUI();
	}

	private void refreshGUI()
	{
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				// facebook
				synchronized (UtilsStride.isFacebookConnected)
				{
					if (!UtilsStride.isFacebookConnected)
					{
						mHandler.post(new Runnable()
						{
							@Override
							public void run()
							{
								fButton.setVisibility(View.VISIBLE);
								fUser.setVisibility(View.INVISIBLE);
								fLogout.setVisibility(View.INVISIBLE);
							}
						});
					}
					else
					{
						final String user = UtilsStride.getFbName();
						if (user != "")
						{
							mHandler.post(new Runnable()
							{
								@Override
								public void run()
								{
									fUser.setText("Connected on facebook as\n      " + user);
									fButton.setVisibility(View.INVISIBLE);
									fUser.setVisibility(View.VISIBLE);
									fLogout.setVisibility(View.VISIBLE);
								}
							});
						}
						else
							UtilsStride.mAsyncRunner.request("me", new SampleRequestListener());
					}
				}

			}
		}).start();

		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				// twitter
				synchronized (UtilsStride.isTwitterConnected)
				{
					if (!UtilsStride.isTwitterConnected)
					{
						mHandler.post(new Runnable()
						{
							@Override
							public void run()
							{
								tButton.setVisibility(View.VISIBLE);
								tUser.setVisibility(View.INVISIBLE);
								tLogout.setVisibility(View.INVISIBLE);
							}
						});
					}
					else
					{
						mHandler.post(new Runnable()
						{
							@Override
							public void run()
							{
								try
								{
									tUser.setText("Connected on twitter as\n          @"
											+ UtilsStride.twitter.getScreenName());
									tButton.setVisibility(View.INVISIBLE);
									tUser.setVisibility(View.VISIBLE);
									tLogout.setVisibility(View.VISIBLE);
								}
								catch (IllegalStateException e)
								{
									e.printStackTrace();
								}
								catch (TwitterException e)
								{
									e.printStackTrace();
								}
							}
						});
					}
				}
			}
		}).start();

		Cursor cursor = managedQuery(StrideDB.CONTENT_URI_PLAYLISTS, null, null, null, null);
		final String[] array_spinner = new String[cursor.getCount()];
		int i = 0;
		while (cursor.moveToNext())
		{
			final int name_index = cursor.getColumnIndex(StrideDB.NAME_P);
			String name = cursor.getString(name_index);
			array_spinner[i++] = name;
		}
		cursor.close();

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				array_spinner);
		playlist_spinner.setAdapter(adapter);
		final String username = UtilsStride.getUserName();
		playlist_spinner.setOnItemSelectedListener(new OnItemSelectedListener()
		{
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3)
			{
				final ContentResolver cr = UtilsStride.mainActivity.getContentResolver();
				ContentValues values = new ContentValues();
				values.put(StrideDB.PLAYLIST_U, array_spinner[pos]);
				cr.update(StrideDB.CONTENT_URI_USERS, values, StrideDB.NAME_U + "='" + username + "'", null);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0)
			{
			}
		});
		
		cursor = managedQuery(StrideDB.CONTENT_URI_USERS, null, StrideDB.NAME_U + "='" + username + "'", null, null);
		if (cursor.moveToNext())
		{
			final int playlist_index = cursor.getColumnIndex(StrideDB.PLAYLIST_U);
			String playlist = cursor.getString(playlist_index);
			for (int j = 0; j < array_spinner.length; j++)
			{
				if (array_spinner[j].equals(playlist))
				{
					playlist_spinner.setSelection(j);
					break;
				}
			}
		}
		cursor.close();
	}

	private void initListenersGUI()
	{

		fButton = (Button) findViewById(R.id.facebook_btn);
		tButton = (Button) findViewById(R.id.twitter_btn);
		fLogout = (Button) findViewById(R.id.facebook_logout_btn);
		tLogout = (Button) findViewById(R.id.twitter_logout_btn);
		music = (Button) findViewById(R.id.music_btn);
		playlist_spinner = (Spinner) findViewById(R.id.playlist_spinner);
		fUser = (TextView) findViewById(R.id.facebook_user);
		tUser = (TextView) findViewById(R.id.twitter_user);

		if (UtilsStride.isFacebookConnected)
		{
			fButton.setVisibility(View.INVISIBLE);
			fUser.setVisibility(View.VISIBLE);
			fLogout.setVisibility(View.VISIBLE);
		}
		if (UtilsStride.isTwitterConnected)
		{
			tButton.setVisibility(View.INVISIBLE);
			tUser.setVisibility(View.VISIBLE);
			tLogout.setVisibility(View.VISIBLE);
		}

		fButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				UtilsStride.mFacebook.authorize(UtilsStride.mainActivity, new String[] {}, new LoginDialogListener());
			}
		});
		tButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				final TabGroupActivity parentActivity = (TabGroupActivity) getParent();
				parentActivity.startChildActivity("TwitterLogin", new Intent(parentActivity, TwitterLogin.class));
			}
		});

		fLogout.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				UtilsStride.disconnectFacebook();
				refreshGUI();
			}
		});
		tLogout.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				UtilsStride.disconnectTwitter();
				refreshGUI();
			}
		});
		music.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				final TabGroupActivity parentActivity = (TabGroupActivity) getParent();
				parentActivity.startChildActivity("FileBrowser", new Intent(parentActivity, FileBrowser.class));
			}
		});

	}

	public final class LoginDialogListener implements DialogListener
	{
		public void onComplete(Bundle values)
		{
			SessionEvents.onLoginSuccess();

			UtilsStride.setFacebookConnected();
			mHandler.post(new Runnable()
			{
				@Override
				public void run()
				{
					refreshGUI();
				}
			});
		}

		public void onFacebookError(FacebookError error)
		{
			SessionEvents.onLoginError(error.getMessage());
		}

		public void onError(DialogError error)
		{
			SessionEvents.onLoginError(error.getMessage());
		}

		public void onCancel()
		{
			SessionEvents.onLoginError("Action Canceled");
		}
	}

	public class SampleRequestListener extends BaseRequestListener
	{
		public void onComplete(final String response)
		{
			try
			{
				// process the response here: executed in background thread
				JSONObject json = Util.parseJson(response);
				final String name = json.getString("name");

				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."

				UtilsStride.setFbName(name);
				mHandler.post(new Runnable()
				{
					@Override
					public void run()
					{
						refreshGUI();
					}
				});
				UtilsStride.insertInDB(StrideDB.MATCH_U, new UsersItem(0, name, "Facebook", "default", ""));
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}
			catch (FacebookError e)
			{
				e.printStackTrace();
			}
		}
	}

}
